package itsm.isperp.framework.security.encoding;

import itsm.isperp.framework.utils.TranscodeUtils;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-12-22
 * @since 1.0
 * 
 */
public class RSAHelper {
	private static String prikey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIBSxSjraaGjW/W6Gmeoq2oT1/7ZUxbgIUIzfYv6tghUCM0nJQ3jrkGRB5WNQicqQG+1M4wevXbR3x9/b2YGnpNNGIqONc2RmxMpkjpRKi8mgiWEgnMaVydtCNJyF7y+6MEgV2AKWo/f5uijKoMTPhPFUPqKJu8ANUvh7XYdYgw5AgMBAAECgYB0LXu+7lN2OfYZ5OHfE4ANy+V0H8HwJf82dnOl9dg0dhB53ITZrFapmepp5bgMyV4JRN5kb7hNCPmfBLsQfdG2dSqFM+nftrynj8ZdlYazubTHJjTBcNnpe5RgTc4kbc5vbEkf5BlH0ul2YvAE1ZuRvYYpc/ILBaIKez4TpmjFuQJBAMbyWqrh21BmUpvTn4m0OtTW45zaNHMZYsheQAsvrl7haBLbKirJ/9HtvTgFbagMFujGVIc+5TNH/V7uUKTrFMcCQQClH5wueWgrQIMqD7H3TteBL/X/u5wo+5t1afLtLqZixxTe9GMrvwFEjAOpl476jI2aAL4LAK//qV6BKjXfVtb/AkEAmdAUU1utgTqrEbkK9p82gQnnDoUR2g89dWaRI1To/ohNO47gyhZEyByDl8Vyo2M9bxivj6UL9ZrqBLRB+0+ZTwJAN0BJeT+EfJx8hxFzYiYOdBrBPI3hJdFy5inKcFSgtgKZWDT8DgI+gVo8S338CJgJNZO0A2h6e5iHl76xAgdDrwJBAI7y29yHmxJ3U76ZwUt8zlxq/TzOYoRwQu1tQ6nHLkQTtY0bdS2vHRgRwoSk30KSXTKB0lJf56PpreYJVVphXvY=";
	private static String pubkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAUsUo62mho1v1uhpnqKtqE9f+2VMW4CFCM32L+rYIVAjNJyUN465BkQeVjUInKkBvtTOMHr120d8ff29mBp6TTRiKjjXNkZsTKZI6USovJoIlhIJzGlcnbQjSche8vujBIFdgClqP3+booyqDEz4TxVD6iibvADVL4e12HWIMOQIDAQAB";

	public static String deciphering(String content) throws Exception {
		String content_jm = "";
		byte[] result1 = TranscodeUtils.hexStr2Bytes(content);// 转化16进制数组
		Cipher cipher = Cipher.getInstance("RSA");
		KeyFactory fac2 = KeyFactory.getInstance("RSA");
		PKCS8EncodedKeySpec keySpec2 = new PKCS8EncodedKeySpec(
				TranscodeUtils.base64StrToByteArray(prikey));
		PrivateKey privateKey = fac2.generatePrivate(keySpec2);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		byte[] result2 = cipher.doFinal(result1);
		content_jm = new String(result2);

		return content_jm;
	}

	/**
	 * 用公要加密
	 * 
	 * @param content
	 *            传入的字符串信息
	 * @return 字符串信息
	 * @throws SysSafeException
	 */
	public static String encryption(String content) throws Exception {
		String content_jm = "";

		Cipher cipher = Cipher.getInstance("RSA");
		KeyFactory fac = KeyFactory.getInstance("RSA");
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
				TranscodeUtils.base64StrToByteArray(pubkey));
		PublicKey publicKey = fac.generatePublic(keySpec);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);

		byte[] result = cipher.doFinal(content.getBytes());
		content_jm = TranscodeUtils.byteArrayToHexStr(result);

		return content_jm;
	}
}
